package com.lyn.usbfile;

import android.annotation.SuppressLint;
import android.content.Context;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.BaseAdapter;
import android.widget.TextView;
import java.util.ArrayList;
import java.util.List;

import me.jahnen.libaums.core.fs.UsbFile;

public class FileAdapter extends BaseAdapter {

    private final Context context;
    private final List<UsbFile> usbFileList = new ArrayList<>();

    public FileAdapter(Context context) {
        this.context = context;
    }

    public void setUsbFileList(List<UsbFile> usbFileList) {
        this.usbFileList.clear();
        if (usbFileList != null) {
            this.usbFileList.addAll(usbFileList);
        }
        notifyDataSetChanged();
    }


    @Override
    public int getCount() {
        return usbFileList.size();
    }

    @Override
    public UsbFile getItem(int position) {
        return usbFileList.get(position);
    }

    @Override
    public long getItemId(int position) {
        return 0;
    }

    @SuppressLint("InflateParams")
    @Override
    public View getView(int position, View convertView, ViewGroup parent) {
        ViewHolder holder;
        if (convertView == null) {
            holder = new ViewHolder();
            convertView = LayoutInflater.from(context).inflate(R.layout.adapter_usbfile, null, false);
            holder.fileIcon = convertView.findViewById(R.id.fileIcon);
            holder.fileName = convertView.findViewById(R.id.fileName);
            convertView.setTag(holder);
        } else {
            holder = (ViewHolder) convertView.getTag();
        }
        UsbFile usbFile = usbFileList.get(position);
        if (usbFile.isDirectory()) {
            holder.fileIcon.setBackgroundResource(R.drawable.directory);
        } else {
            holder.fileIcon.setBackgroundResource(R.drawable.file);
        }
        holder.fileName.setText(usbFile.getName());
        return convertView;
    }


    static class ViewHolder {
        FileIconView fileIcon;
        TextView fileName;
    }
}
